<template>
  <div class="app-container">
    <!-- 基础信息卡片 -->
    <el-card class="base-info-card" shadow="never">
      <div slot="header" class="base-info-title">
        <span>基础信息</span>
      </div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="140px" size="small" class="base-info-form">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="入库单编号" prop="recpt_code">
              <div class="input-switch-group">
                <el-input v-model="form.recpt_code" placeholder="自动生成编号" :readonly="form.auto_code || !!form.recpt_id" />
                <el-switch v-model="form.auto_code" style="margin-left: 8px;" @change="handleAutoCodeChange" :disabled="!!form.recpt_id" />
                <span class="switch-label">自动生成</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库单名称" prop="recpt_name">
              <el-input v-model="form.recpt_name" placeholder="请输入入库单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplier_name">
              <el-input v-model="form.supplier_name" placeholder="采购订单关联的供应商" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="采购订单" prop="po_code">
              <el-input v-model="form.po_code" placeholder="请选择采购订单" readonly>
                <template slot="append">
                  <el-button icon="el-icon-search" @click="handleOpenOrderDialog" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次编号" prop="batch_code">
              <el-input v-model="form.batch_code" placeholder="请输入批次编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="入库仓库" prop="warehouse_id">
              <el-select v-model="form.warehouse_id" placeholder="请选择入库仓库" @change="handleWarehouseChange">
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouse_id"
                  :label="item.warehouse_name"
                  :value="item.warehouse_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 入库物料明细 -->
    <div class="goods-section">
      <div style="margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;">
        <span style="font-weight: bold;">入库物料明细</span>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddItem">添加入库商品</el-button>
      </div>
      <el-table :data="pagedItemList" style="width: 100%" border>
        <el-table-column prop="goods_code" label="物料编号" align="center" width="150" />
        <el-table-column prop="goods_name" label="物料名称" align="center" width="180" />
        <el-table-column prop="stock_sfn" label="规格型号" align="center" show-overflow-tooltip/>
        <el-table-column prop="unit_name" label="单位" align="center" width="80" />
        <el-table-column prop="arrived_num" label="待入库数量" align="center" />
        <el-table-column prop="treat_list_num" label="待上架数量" align="center" />
        <el-table-column prop="list_num" label="已上架数量" align="center" />
        <el-table-column prop="receipt_num" label="本次入库数量" align="center" width="160">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.receipt_num"
              :min="0"
              :max="calculateMaxReceiptQuantity(scope.row)"
              size="mini"
              :controls="true"
              :precision="2"
              @change="handleQuantityChange(scope.$index + (itemQuery.pageNum - 1) * itemQuery.pageSize)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="warehouse_name" label="仓库" align="center" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.warehouse_id">{{ getWarehouseName(scope.row.warehouse_id) }}</span>
            <span v-else style="color: #C0C4CC;">请选择仓库</span>
          </template>
        </el-table-column>
        <el-table-column prop="area_name" label="库区" align="center" width="120">
          <template slot-scope="scope">
            <el-select v-model="scope.row.location_id" placeholder="请选择库区" size="mini" @change="(val) => handleAreaChange(val, scope.$index + (itemQuery.pageNum - 1) * itemQuery.pageSize)">
              <el-option
                v-for="item in getAreaOptions(scope.row.warehouse_id)"
                :key="item.location_id"
                :label="item.location_name"
                :value="item.location_id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="location_name" label="库位" align="center" width="120">
          <template slot-scope="scope">
            <el-select v-model="scope.row.area_id" placeholder="请选择库位" size="mini">
              <el-option
                v-for="item in getLocationOptions(scope.row.location_id)"
                :key="item.area_id"
                :label="item.area_name"
                :value="item.area_id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="production_date" label="生产日期" align="center" width="140">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.production_date"
              type="date"
              placeholder="选择日期"
              size="mini"
              style="width: 120px"
              value-format="yyyy-MM-dd"
              @change="handleProductionDateChange(scope.$index + (itemQuery.pageNum - 1) * itemQuery.pageSize)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="expiry_date" label="有效期" align="center" width="140">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.expiry_date"
              type="date"
              placeholder="选择日期"
              size="mini"
              style="width: 120px"
              value-format="yyyy-MM-dd"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="removeItem(scope.$index + (itemQuery.pageNum - 1) * itemQuery.pageSize)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加物料明细的分页组件 -->
      <div style="margin: 16px 0; text-align: right;">
        <pagination
          v-show="itemList.length > 0"
          :total="itemList.length"
          :page.sync="itemQuery.pageNum"
          :limit.sync="itemQuery.pageSize"
          @pagination="handleItemPagination"
        />
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div style="margin-top: 30px; text-align: center;">
      <el-button type="primary" @click="handleSubmit">保存</el-button>
      <el-button type="success" @click="handleSubmitAndApprove">保存并提交</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>

    <!-- 采购订单选择弹窗 -->
    <el-dialog title="选择采购订单" :visible.sync="orderDialogVisible" width="1200px">
      <div style="margin-bottom: 10px; display: flex; gap: 10px;">
        <el-input v-model="orderQuery.po_code" placeholder="请输入采购订单编号" size="small" style="width: 180px;" />
        <el-input v-model="orderQuery.po_name" placeholder="请输入采购订单名称" size="small" style="width: 180px;" />
        <el-button type="primary" size="small" @click="handleOrderSearch">搜索</el-button>
        <el-button size="small" @click="handleOrderReset">重置</el-button>
      </div>
      <el-table 
        :data="orderList" 
        style="width: 100%" 
        border 
        @row-click="selectOrderAndClose" 
        highlight-current-row
      >
        <el-table-column prop="po_code" label="采购订单编号" align="center" width="150" />
        <el-table-column prop="po_name" label="采购订单名称" align="center" />
        <el-table-column prop="supplier_name" label="供应商名称" align="center" width="180" />
        <el-table-column prop="batch_code" label="批次编号" align="center" width="170" />
        <el-table-column prop="arrived_line_cnt" label="可入库商品数" align="center" width="120" />
        <el-table-column prop="purchase_type" label="采购类型" align="center" width="120" />
        <el-table-column prop="status" label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '2' ? 'primary' : 'success'">
              {{ scope.row.status === '2' ? '采购中' : '到货' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 16px 0; text-align: right;">
        <pagination
          v-show="orderQuery.total > 0"
          :total="orderQuery.total"
          :page.sync="orderQuery.pageNum"
          :limit.sync="orderQuery.pageSize"
          @pagination="getOrderList"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    
    <!-- 入库商品选择弹窗 -->
    <el-dialog title="选择入库商品" :visible.sync="goodsDialogVisible" width="1600px">
      <div style="margin-bottom: 10px; display: flex; gap: 10px;">
        <el-input v-model="goodsQuery.goods_code" placeholder="请输入商品编号" size="small" style="width: 180px;" />
        <el-input v-model="goodsQuery.goods_name" placeholder="请输入商品名称" size="small" style="width: 180px;" />
        <el-button type="primary" size="small" @click="handleGoodsSearch">搜索</el-button>
        <el-button size="small" @click="handleGoodsReset">重置</el-button>
      </div>
      <el-table 
        :data="goodsList" 
        style="width: 100%" 
        border 
        v-loading="goodsLoading"
        @selection-change="handleGoodsSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="po_code" label="采购编号" align="center" width="150" />
        <el-table-column prop="po_name" label="采购名称" align="center" width="180" />
        <el-table-column prop="goods_code" label="商品编号" align="center" width="150" />
        <el-table-column prop="goods_name" label="商品名称" align="center" show-overflow-tooltip />
        <el-table-column prop="stock_sfn" label="规格型号" align="center" width="180" show-overflow-tooltip />
        <el-table-column prop="unit_name" label="单位" align="center" width="80" />
        <el-table-column prop="arrived_num" label="待入库数量" align="center" width="100">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.arrived_num || 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="treat_list_num" label="待上架数量" align="center" width="120">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.treat_list_num || 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="list_num" label="已上架数量" align="center" width="120">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.list_num || 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="batch_code" label="批次号" align="center" width="170" show-overflow-tooltip />
      </el-table>
      <div style="margin: 16px 0; text-align: right;">
        <pagination
          v-show="goodsQuery.total > 0"
          :total="goodsQuery.total"
          :page.sync="goodsQuery.pageNum"
          :limit.sync="goodsQuery.pageSize"
          @pagination="fetchGoodsList"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="goodsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmGoodsSelect">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"
import { selectWarehouse } from "@/views/ck/js/setup"
import { selectRecptLine_feedback,listPurchaseOrderDetails, getPurchaseOrderDetail,addItemReceipt, getListArrived } from "@/views/ck/js/receipt"
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";

export default {
  name: 'AddItemReceipt',
  components: {
    Pagination
  },
  data() {
    return {
      // 入库单表单数据
      form: {
        recpt_id: '', // 入库单ID
        recpt_code: '', // 入库单编号
        auto_code: true, // 是否自动生成编号
        recpt_name: '', // 入库单名称
        po_id: '', // 采购订单ID
        po_code: '', // 采购订单编号
        po_name: '', // 采购订单名称
        batch_code: '', // 批次编号
        supplier_id: '', // 供应商ID
        supplier_name: '', // 供应商名称
        storage_type: '1', // 入库类型 1 采购入库 2 生产退料 3 产品入库
        warehouse_id: '', // 仓库ID
        warehouse_name: '', // 仓库名称
        status: '1', // 状态，默认为待提交
        remark: '', // 备注
        create_by: '', // 创建人
        update_by: '' // 更新人
      },
      // 表单验证规则
      rules: {
        recpt_code: [
          { required: true, message: '请生成入库单编号', trigger: ['blur', 'change'] }
        ],
        recpt_name: [
          { required: true, message: '请输入入库单名称', trigger: 'blur' }
        ],
        po_code: [
          { required: true, message: '请选择采购订单', trigger: 'change' }
        ],
        // 移除供应商的必填验证
        warehouse_id: [
          { required: true, message: '请选择入库仓库', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      // 入库物料明细
      itemList: [],
      // 物料明细分页
      itemQuery: {
        pageNum: 1,
        pageSize: 10
      },
      // 仓库选项
      warehouseOptions: [],
      // 后台返回的完整仓库-库区-库位数据
      warehouseData: [],
      // 采购订单选择对话框
      orderDialogVisible: false,
      orderList: [],
      orderQuery: {
        pageNum: 1,
        pageSize: 10,
        po_code: '',
        po_name: '',
        total: 0
      },
      // 质检单选择对话框
      iqcDialogVisible: false,
      iqcSelected: null,
      // 入库商品选择对话框
      goodsDialogVisible: false,
      goodsList: [],
      goodsLoading: false,
      goodsQuery: {
        po_code: '',
        goods_code: '',
        goods_name: '',
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      selectedGoods: [] // 已选择商品数组
    }
  },
  computed: {
    // 计算属性，根据当前分页获取物料明细数据
    pagedItemList() {
      const start = (this.itemQuery.pageNum - 1) * this.itemQuery.pageSize;
      const end = start + this.itemQuery.pageSize;
      return this.itemList.slice(start, end);
    }
  },
  created() {
    // 从路由查询字符串中获取数据
    if(this.$route.query.order != undefined){
      this.form = JSON.parse(this.$route.query.order);
      console.log("form:",this.form);
    }else{
      // 如果是自动生成编号，获取编号
      if (this.form.auto_code) {
        this.getAutoCode();
      }
    }
    
    this.selectedGoods = []; // 初始化已选择商品数组
    this.getWarehouseList(); // 获取仓库-库区-库位数据

    /* // 如果入库单ID为空，则查询采购订单行信息
    if(this.form.recpt_id != ''){
      this.findOrderLine_id();
    } */
  },
  methods: {
    //根据编号查询采购订单行信息
    findOrderLine_id(){
      let recpt_id = this.form.recpt_id;
      selectRecptLine_feedback(recpt_id).then(response => {
        this.goodsList = response.rows || [];
        
        // 无论如何，先清空原有的物料明细数据
        this.itemList = [];
        
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          // 获取已选仓库的第一个库区和第一个库位
          let firstLocation = null;
          let firstArea = null;
          
          if (this.form.warehouse_id) {
            const selectedWarehouse = this.warehouseData.find(item => item.warehouse_id === this.form.warehouse_id);
            
            if (selectedWarehouse && selectedWarehouse.locations && selectedWarehouse.locations.length > 0) {
              firstLocation = selectedWarehouse.locations[0];
              
              if (firstLocation && firstLocation.areas && firstLocation.areas.length > 0) {
                firstArea = firstLocation.areas[0];
              }
            }
          }
          
          // 获取当前日期和三年后的日期
          const today = new Date().toISOString().slice(0, 10);
          const threeYearsLater = new Date(new Date().setFullYear(new Date().getFullYear() + 3)).toISOString().slice(0, 10);
          
          // 将所有商品添加到物料明细表格
          this.goodsList.forEach(item => {
            const newItem = {
              line_id: item.line_id,
              order_line_id: item.order_line_id,
              goods_code: item.goods_code,
              goods_name: item.goods_name,
              stock_sfn: item.stock_sfn,
              unit_name: item.unit_name,
              arrived_num: item.arrived_num || 0,
              treat_list_num: item.treat_list_num || 0,
              list_num: item.list_num || 0,
              receipt_num: item.recived_num || 0, // 使用已有的入库数量
              unit_price: item.unit_price || 0,
              total_price: '0.00',
              material_subcategory_id: item.material_subcategory_id,
              material_classification_id: item.material_classification_id,
              warehouse_id: this.form.warehouse_id,
              warehouse_name: this.form.warehouse_name,
              location_id: firstLocation ? firstLocation.location_id : '',
              location_name: firstLocation ? firstLocation.location_name : '',
              area_id: firstArea ? firstArea.area_id : '',
              area_name: firstArea ? firstArea.area_name : '',
              remark: '',
              production_date: today,
              expiry_date: threeYearsLater
            };
            
            // 计算总价
            this.calculateTotalPrice(newItem);
            this.itemList.push(newItem);
          });
          
          // 重置物料明细的分页为第一页
          this.itemQuery.pageNum = 1;
          
          this.$message.success(`已加载 ${this.itemList.length} 个商品到物料明细`);
        } else {
          this.$message.warning('该采购订单没有可入库的商品');
        }
      })
    },

    /**
     * 计算物料行的总价
     * @param {Object} row 物料行数据
     * @return {String} 格式化后的总价
     */
    calculateTotalPrice(row) {
      const qty = Number(row.receipt_num) || 0;
      const price = Number(row.unit_price) || 0;
      const total = Math.round(qty * price * 100) / 100;
      row.total_price = total.toFixed(2);
      return total.toFixed(2);
    },
    
    /**
     * 处理数量变更，重新计算总价
     */
    handleQuantityChange(index) {
      const row = this.itemList[index];
      this.calculateTotalPrice(row);
    },
    
    /**
     * 处理物料明细分页变化
     */
    handleItemPagination(val) {
      this.itemQuery.pageNum = val.page;
      this.itemQuery.pageSize = val.limit;
    },
    
    /**
     * 获取仓库列表
     */
    getWarehouseList() {
      // 示例API调用，实际使用时需要替换为真实的API
      selectWarehouse().then(response => {
        this.warehouseData = response.dataList;
  
        // 提取仓库选项
        this.warehouseOptions = this.warehouseData.map(item => ({
          warehouse_id: item.warehouse_id,
          warehouse_name: item.warehouse_name
        }));

        // 如果入库单ID为空，则查询采购订单行信息
        if(this.form.recpt_id != ''){
          this.findOrderLine_id();
        }
      }).catch(error => {
        console.error('获取仓库列表失败:', error);
        this.$message.error('获取仓库列表失败');
      });
    },
    
    /**
     * 获取仓库名称
     */
    getWarehouseName(warehouseId) {
      const warehouse = this.warehouseOptions.find(item => item.warehouse_id === warehouseId);
      return warehouse ? warehouse.warehouse_name : '';
    },
    
    /**
     * 获取特定仓库下的库区选项
     */
    getAreaOptions(warehouseId) {
      if (!warehouseId) return [];
      
      const warehouse = this.warehouseData.find(item => item.warehouse_id === warehouseId);
      return warehouse ? warehouse.locations || [] : [];
    },
    
    /**
     * 获取特定库区下的库位选项
     */
    getLocationOptions(locationId) {
      if (!locationId) return [];
      for (const warehouse of this.warehouseData) {
        const locations = warehouse.locations.find(item => item.location_id === locationId);
        if (locations) {
          return locations.areas || [];
        }
      }
      
      return [];
    },
    
    /**
     * 处理仓库变更
     */
    handleWarehouseChange(warehouseId) {
      // 找到对应的仓库名称
      const warehouse = this.warehouseOptions.find(item => item.warehouse_id === warehouseId);
      if (warehouse) {
        this.form.warehouse_name = warehouse.warehouse_name;
      }
      
      // 获取该仓库下的第一个库区和第一个库位
      const selectedWarehouse = this.warehouseData.find(item => item.warehouse_id === warehouseId);
      let firstLocation = null;
      let firstArea = null;
      
      if (selectedWarehouse && selectedWarehouse.locations && selectedWarehouse.locations.length > 0) {
        firstLocation = selectedWarehouse.locations[0];
        
        if (firstLocation && firstLocation.areas && firstLocation.areas.length > 0) {
          firstArea = firstLocation.areas[0];
        }
      }
      
      // 更新所有物料的仓库信息
      this.itemList.forEach(item => {
        item.warehouse_id = warehouseId;
        item.warehouse_name = warehouse ? warehouse.warehouse_name : '';
        
        // 自动选择第一个库区
        if (firstLocation) {
          item.location_id = firstLocation.location_id;
          item.location_name = firstLocation.location_name;
        } else {
          item.location_id = '';
          item.location_name = '';
        }
        
        // 自动选择第一个库位
        if (firstArea) {
          item.area_id = firstArea.area_id;
          item.area_name = firstArea.area_name;
        } else {
          item.area_id = '';
          item.area_name = '';
        }
      });
    },
    
    /**
     * 处理单个物料行的库区变更
     */
    handleAreaChange(locationId, index) {
      // 获取选中的库区信息
      for (const warehouse of this.warehouseData) {
        const location = (warehouse.locations || []).find(loc => loc.location_id === locationId);
        if (location) {
          this.itemList[index].location_name = location.location_name;
          // 重置该行的库位
          this.itemList[index].area_id = '';
          this.itemList[index].area_name = '';
          break;
        }
      }
    },
    
    /**
     * 打开采购订单选择对话框
     */
    handleOpenOrderDialog() {
      this.orderDialogVisible = true;
      this.getOrderList();
    },
    
    /**
     * 打开质检单选择对话框
     */
    handleOpenIqcDialog() {
      this.iqcDialogVisible = true;
      // 获取质检单列表的方法，待实现
    },
    
    /**
     * 获取采购订单列表
     */
    getOrderList() {
      getListArrived(this.orderQuery).then(response => {
        this.orderList = response.rows || [];
        this.orderQuery.total = response.total || 0;
      }).catch(error => {
        console.error('获取采购订单列表失败:', error);
        this.$message.error('获取采购订单列表失败');
      });
    },
    
    /**
     * 搜索采购订单
     */
    handleOrderSearch() {
      this.orderQuery.pageNum = 1;
      this.getOrderList();
    },
    
    /**
     * 重置采购订单搜索条件
     */
    handleOrderReset() {
      this.orderQuery = {
        pageNum: 1,
        pageSize: 10,
        po_code: '',
        po_name: '',
        status: '2',
        total: 0
      };
      this.getOrderList();
    },
    
    /**
     * 选择采购订单行并关闭弹窗
     * @param {Object} order 选中的订单行数据
     */
    selectOrderAndClose(order) {
      if (!order) {
        this.$message.warning('请选择一个采购订单');
        return;
      }
      
      // 设置表单中的采购订单相关字段
      this.form.po_id = order.po_id;
      this.form.po_code = order.po_code;
      this.form.po_name = order.po_name;
      this.form.supplier_id = order.supplier_id;
      this.form.supplier_name = order.supplier_name;
      this.form.batch_code = order.batch_code; // 设置批次编号
      
      // 每次选择采购订单时都更新入库单名称
      const now = new Date();
      const dateStr = now.toISOString().slice(0, 10).replace(/-/g, ''); // 格式如: 20230615
      const timeStr = now.getHours().toString().padStart(2, '0') + 
                     now.getMinutes().toString().padStart(2, '0');
      this.form.recpt_name = `${order.po_name}入库单-${dateStr}${timeStr}`;
      
      // 关闭采购订单选择弹窗
      this.orderDialogVisible = false;
      
      // 显示加载状态
      const loading = this.$loading({
        lock: true,
        text: '正在加载采购订单商品数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 更新查询参数
      const queryParams = {
        po_code: order.po_code,
        pageNum: 1,
        pageSize: 999 // 先获取所有数据，以便初始化物料明细表格
      };
      
      listPurchaseOrderDetails(queryParams).then(response => {
        loading.close();

        this.goodsList = response.rows || [];
        
        // 无论如何，先清空原有的物料明细数据
        this.itemList = [];
        
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          // 获取已选仓库的第一个库区和第一个库位
          let firstLocation = null;
          let firstArea = null;
          
          if (this.form.warehouse_id) {
            const selectedWarehouse = this.warehouseData.find(item => item.warehouse_id === this.form.warehouse_id);
            
            if (selectedWarehouse && selectedWarehouse.locations && selectedWarehouse.locations.length > 0) {
              firstLocation = selectedWarehouse.locations[0];
              
              if (firstLocation && firstLocation.areas && firstLocation.areas.length > 0) {
                firstArea = firstLocation.areas[0];
              }
            }
          }
          
          // 获取当前日期和三年后的日期
          const today = new Date().toISOString().slice(0, 10);
          const threeYearsLater = new Date(new Date().setFullYear(new Date().getFullYear() + 3)).toISOString().slice(0, 10);
          
          // 将所有商品添加到物料明细表格
          this.goodsList.forEach(item => {
            const newItem = {
              order_line_id: item.line_id,
              goods_code: item.goods_code,
              goods_name: item.goods_name,
              stock_sfn: item.stock_sfn,
              unit_name: item.unit_name,
              arrived_num: item.arrived_num || 0,
              treat_list_num: item.treat_list_num || 0,
              list_num: item.list_num || 0,
              receipt_num: this.calculateMaxReceiptQuantity(item), // 默认本次入库数量为待入库数量和待上架数量之和
              unit_price: item.unit_price || 0,
              total_price: '0.00',
              material_subcategory_id: item.material_subcategory_id,
              material_classification_id: item.material_classification_id,
              warehouse_id: this.form.warehouse_id,
              warehouse_name: this.form.warehouse_name,
              location_id: firstLocation ? firstLocation.location_id : '',
              location_name: firstLocation ? firstLocation.location_name : '',
              area_id: firstArea ? firstArea.area_id : '',
              area_name: firstArea ? firstArea.area_name : '',
              remark: '',
              production_date: today,
              expiry_date: threeYearsLater
            };
            
            // 计算总价
            this.calculateTotalPrice(newItem);
            this.itemList.push(newItem);
          });
          
          // 重置物料明细的分页为第一页
          this.itemQuery.pageNum = 1;
          
          this.$message.success(`已加载 ${this.itemList.length} 个商品到物料明细`);
        } else {
          this.$message.warning('该采购订单没有可入库的商品');
        }
      }).catch(error => {
        loading.close();
        // 发生错误时也清空物料明细
        this.itemList = [];
        console.error('获取采购订单商品失败:', error);
        this.$message.error('获取采购订单商品失败');
      });
    },
    
    /**
     * 加载采购订单物料明细
     * @param {string} poId 采购订单ID
     */
    loadOrderItems(poId) {
      getPurchaseOrderDetail(poId).then(response => {
        if (response.code === 200) {
          const items = response.data || [];
          const today = new Date().toISOString().slice(0, 10);
          const threeYearsLater = new Date(new Date().setFullYear(new Date().getFullYear() + 3)).toISOString().slice(0, 10);
          
          this.itemList = items.map(item => {
            return {
              ...item,
              receipt_num: 0, // 默认本次入库数量为0
              warehouse_id: this.form.warehouse_id,
              warehouse_name: this.form.warehouse_name,
              area_id: '', // 默认库区为空
              area_name: '',
              location_id: '', // 默认库位为空
              location_name: '',
              total_price: '0.00',
              production_date: today, // 生产日期默认为当天
              expiry_date: threeYearsLater // 有效期为生产日期的3年后
            };
          });
        } else {
          this.$message.error(response.msg || '获取采购订单详情失败');
        }
      }).catch(error => {
        console.error('获取采购订单详情失败:', error);
        this.$message.error('获取采购订单详情失败');
      });
    },
    
    /**
     * 确认选择质检单
     */
    confirmIqcSelect() {
      // 待实现
      this.iqcDialogVisible = false;
    },
    
    /**
     * 处理自动生成编号开关变化
     */
    handleAutoCodeChange(val) {
      if (val) {
        if(this.form.recpt_id == ''){
          this.getAutoCode();
        }
      } else {
        if(this.form.recpt_id == ''){
          this.form.recpt_code = '';
        }
      }
    },
    
    /**
     * 获取自动生成的编号
     */
    getAutoCode() {
      getAutoNumbers(29).then(res => { //29 是入库单的编号类型
        if (res.code === 200) {
          this.form.recpt_code = res.msg;
        } else {
          this.$message.error(res.msg || '获取编号失败');
          this.form.auto_code = false;
        }
      }).catch(err => {
        this.$message.error('获取编号请求异常');
        this.form.auto_code = false;
      });
    },
    
    /**
     * 处理表单提交
     */
    async handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return;
        
        // 检查是否有物料行
        if (this.itemList.length === 0) {
          this.$message.warning('请添加入库物料');
          return;
        }
        
        // 验证每一行物料的本次入库数量、库区和库位
        let isValid = true;
        for (let i = 0; i < this.itemList.length; i++) {
          const item = this.itemList[i];
          
          // 验证本次入库数量必须大于0
          if (item.receipt_num <= 0) {
            this.$message.warning(`第${i+1}行物料"${item.goods_name}"的本次入库数量必须大于0`);
            isValid = false;
            break;
          }
          
          // 验证库区和库位必须选择
          if (!item.location_id) {
            this.$message.warning(`第${i+1}行物料"${item.goods_name}"未选择库区，请选择`);
            isValid = false;
            break;
          }
          if (!item.area_id) {
            this.$message.warning(`第${i+1}行物料"${item.goods_name}"未选择库位，请选择`);
            isValid = false;
            break;
          }
        }
        
        if (!isValid) return;
        
        // 获取有效的入库物料行（入库数量大于0）
        const validItems = this.itemList.filter(item => item.receipt_num > 0);
        
        // 显示提交中的加载状态
        const loading = this.$loading({
          lock: true,
          text: '正在保存数据，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        if (this.form.auto_code && !this.form.recpt_id) {
          try {
            const res = await getAutoNumbersConsume(29);
            if (res.code === 200) {
              this.form.recpt_code = res.msg;
            } else {
              this.$message.error(res.msg || '获取最终编号失败');
              loading.close();
              return;
            }
          } catch (err) {
            this.$message.error('获取最终编号请求异常');
            loading.close();
            return;
          }
        }
        
        // 设置创建人和更新人
        this.form.create_by = this.$store.getters.name;
        this.form.update_by = this.form.create_by;
        
        // 构造提交数据
        const submitData = {
          itemRecpt: this.form,
          listItemDetail: validItems
        };
        console.log("提交数据：",submitData);
        
        // 调用后端接口保存数据
        addItemReceipt(submitData).then(response => {
          loading.close();
          if (response.code === 200) {
            this.$message.success('入库单创建成功');
            this.$router.push('/ck/PurchaseInventory');
          } else {
            this.$message.error(response.msg || '入库单创建失败');
          }
        }).catch(error => {
          loading.close();
          console.error('创建入库单失败:', error);
          this.$message.error('系统错误，请稍后重试');
        });
      });
    },
    
    /**
     * 保存并提交审核
     */
    handleSubmitAndApprove() {
      this.form.status = '2'; // 设置状态为待质检
      this.handleSubmit();
    },
    
    /**
     * 取消操作
     */
    handleCancel() {
      this.$router.back();
    },

    /**
     * 添加入库商品
     */
    handleAddItem() {
      // 检查是否已选择采购订单
      if (!this.form.po_code) {
        this.$message.warning('请先选择采购订单');
        return;
      }
      
      // 设置查询参数，确保包含采购订单编号
      this.goodsQuery.po_code = this.form.po_code;
      
      this.goodsDialogVisible = true;
      this.fetchGoodsList(); // 打开对话框时自动加载可入库商品
    },

    /**
     * 获取入库商品列表
     */
    fetchGoodsList() {
      this.goodsLoading = true;
      
      // 确保查询参数中包含所需信息
      const queryParams = {
        pageNum: this.goodsQuery.pageNum,
        pageSize: this.goodsQuery.pageSize,
        po_code: this.goodsQuery.po_code || this.form.po_code,
        goods_code: this.goodsQuery.goods_code,
        goods_name: this.goodsQuery.goods_name
      };
      
      listPurchaseOrderDetails(queryParams).then(response => {
        this.goodsList = response.rows || [];
        this.goodsQuery.total = response.total || 0;
        this.goodsLoading = false;
      }).catch(error => {
        console.error('获取入库商品列表失败:', error);
        this.$message.error('获取入库商品列表失败');
        this.goodsLoading = false;
      });
    },

    /**
     * 处理入库商品选择
     */
    handleGoodsSelectionChange(selection) {
      this.selectedGoods = selection;
    },

    /**
     * 搜索入库商品
     */
    handleGoodsSearch() {
      this.goodsQuery.pageNum = 1;
      this.fetchGoodsList();
    },

    /**
     * 重置入库商品搜索条件
     */
    handleGoodsReset() {
      this.goodsQuery = {
        pageNum: 1,
        pageSize: 10,
        po_code: this.form.po_code, // 保留采购订单编号，因为需要根据它过滤商品
        goods_code: '',
        goods_name: '',
        total: 0
      };
      this.fetchGoodsList();
    },

    /**
     * 确认选择入库商品
     */
    confirmGoodsSelect() {
      if (!this.selectedGoods || this.selectedGoods.length === 0) {
        this.$message.warning('请选择至少一个入库商品');
        return;
      }

      // 选择的商品
      const goods = this.selectedGoods;
      
      // 获取已选仓库的第一个库区和第一个库位
      let firstLocation = null;
      let firstArea = null;
      
      if (this.form.warehouse_id) {
        const selectedWarehouse = this.warehouseData.find(item => item.warehouse_id === this.form.warehouse_id);
        
        if (selectedWarehouse && selectedWarehouse.locations && selectedWarehouse.locations.length > 0) {
          firstLocation = selectedWarehouse.locations[0];
          
          if (firstLocation && firstLocation.areas && firstLocation.areas.length > 0) {
            firstArea = firstLocation.areas[0];
          }
        }
      }
      
      goods.forEach(item => {
        // 查找是否已存在相同商品
        const existingIndex = this.itemList.findIndex(
          existingItem => existingItem.goods_code === item.goods_code
        );
        
        if (existingIndex !== -1) {
          console.log("商品已存在，数量加1:",item.goods_code);
          // 如果商品已存在，数量加1
          const currentNum = this.itemList[existingIndex].receipt_num || 0;
          // 确保不超过最大可入库数量
          const maxQuantity = this.calculateMaxReceiptQuantity(item);
          this.itemList[existingIndex].receipt_num = Math.min(currentNum + 1, maxQuantity);
          // 重新计算总价
          this.calculateTotalPrice(this.itemList[existingIndex]);
        } else {
          // 如果商品不存在，添加新商品，默认数量为1
          const newItem = {
            order_line_id: item.line_id,
            goods_code: item.goods_code,
            goods_name: item.goods_name,
            stock_sfn: item.stock_sfn,
            unit_name: item.unit_name,
            arrived_num: item.arrived_num || 0,
            treat_list_num: item.treat_list_num || 0,
            list_num: item.list_num || 0,
            receipt_num: Math.min(1, this.calculateMaxReceiptQuantity(item)), // 默认本次入库数量为1，但不超过最大可入库数量
            unit_price: item.unit_price || 0,
            total_price: '0.00',
            material_subcategory_id: item.material_subcategory_id,
            material_classification_id: item.material_classification_id,
            warehouse_id: this.form.warehouse_id,
            warehouse_name: this.form.warehouse_name,
            location_id: firstLocation ? firstLocation.location_id : '', // 默认选择第一个库区
            location_name: firstLocation ? firstLocation.location_name : '',
            area_id: firstArea ? firstArea.area_id : '', // 默认选择第一个库位
            area_name: firstArea ? firstArea.area_name : '',
            remark: '',
            production_date: new Date().toISOString().slice(0, 10), // 生产日期默认为当天
            expiry_date: new Date(new Date().setFullYear(new Date().getFullYear() + 3)).toISOString().slice(0, 10) // 有效期为生产日期的3年后
          };
          
          // 计算总价
          this.calculateTotalPrice(newItem);
          this.itemList.push(newItem);
        }
      });

      this.goodsDialogVisible = false;
      this.$message.success('商品添加成功');
    },

    /**
     * 格式化货币
     */
    formatCurrency(value) {
      if (value === null || value === undefined) return '0.00';
      return Number(value).toFixed(2);
    },

    /**
     * 格式化数字
     */
    formatNumber(value) {
      if (value === null || value === undefined) return '0';
      return Number(value).toLocaleString();
    },

    /**
     * 处理生产日期变更
     */
    handleProductionDateChange(index) {
      const row = this.itemList[index];
      // 如果生产日期选择为空，则有效期也设为空
      if (!row.production_date) {
        row.expiry_date = '';
        return;
      }
      // 有效期默认为生产日期的3年后
      row.expiry_date = new Date(new Date(row.production_date).setFullYear(new Date(row.production_date).getFullYear() + 3)).toISOString().slice(0, 10);
    },

    /**
     * 计算最大可入库数量（待入库数量 + 待上架数量）
     * 处理小数计算问题
     */
    calculateMaxReceiptQuantity(row) {
      // 使用parseFloat确保转换为数字，并处理null和undefined的情况
      const arrivedNum = parseFloat(row.arrived_num) || 0;
      const treatListNum = parseFloat(row.treat_list_num) || 0;
      
      // 使用toFixed和parseFloat处理小数精度问题
      const maxQuantity = parseFloat((arrivedNum + treatListNum).toFixed(2));
      
      return maxQuantity > 0 ? maxQuantity : 9999; // 如果计算结果小于等于0，则使用默认值9999
    },

    /**
     * 移除物料行项目
     * @param {Number} index 要移除的项目索引
     */
    removeItem(index) {
      this.$confirm('确认移除该物料行项目吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.itemList.splice(index, 1);
        this.$message({
          type: 'success',
          message: '移除成功!'
        });
      }).catch(() => {
        // 取消移除操作
      });
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.base-info-card {
  margin-bottom: 20px;
  border-radius: 4px;
  background: #fff;
}

.base-info-title {
  font-weight: bold;
  font-size: 16px;
  padding: 4px 0;
}

.base-info-form {
  padding: 0 10px 0 0;
}

.base-info-form .el-form-item {
  margin-bottom: 16px;
}

.goods-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  margin-top: 20px;
  width: 100%;
  box-sizing: border-box;
}

.goods-section .el-table {
  width: 100% !important;
}

.goods-section .el-table__body-wrapper,
.goods-section .el-table__header-wrapper {
  width: 100% !important;
}

.input-switch-group {
  display: flex;
  align-items: center;
}

.input-switch-group .el-input {
  flex: 1;
}

.switch-label {
  margin-left: 6px;
  color: #909399;
  font-size: 14px;
  white-space: nowrap;
}

@media (max-width: 1200px) {
  .base-info-form .el-col-8 {
    width: 100%;
    max-width: 100%;
    flex: 0 0 100%;
  }
}
</style> 